<template>
  <div>
    <van-search
      shape="round"
      background="#ff734c"
      v-model="keyWord"
      show-action
      label="商品"
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <h3>历史搜索</h3>
    <div class="search-his">
      <div class="his" @click="clickHis(h)" v-for="h in his" :key="h">
        {{h}}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      keyWord: '',
      his: localStorage.getItem('his')
        ? JSON.parse(localStorage.getItem('his'))
        : []
    }
  },
  methods: {
    clickHis (h) {
      // 点击历史记录
      this.keyWord = h
      this.onSearch()
    },
    onSearch () {
      // 存缓存
      let his = localStorage.getItem('his')
        ? JSON.parse(localStorage.getItem('his'))
        : []
      his.unshift(this.keyWord)
      // 数组去重
      his = [...new Set(his)]
      if (his.length > 5) {
        his.pop()
      }
      localStorage.setItem('his', JSON.stringify(his))
      this.$router.push({
        path: '/searchLists',
        query: {
          word: this.keyWord
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.search-his{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  .his{
    padding: 10px 20px;
    background-color: rgb(233, 207, 207);
    border-radius: 5px;
    margin-top: 5px;
  }
}
</style>
